import 'dart:io';

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:hospitable_rental/utils/common_toast.dart';
import 'package:hospitable_rental/utils/config.dart';

class DioHttp {
  Dio? _client;

  BuildContext? context;

  static DioHttp of(BuildContext context) {
    return DioHttp._internal(context);
  }

  DioHttp._internal(BuildContext context) {
    if (_client == null || context != this.context) {
      this.context = context;
      var options = BaseOptions(
        baseUrl: Config.BaseUrl,
        connectTimeout: 5000,
        receiveTimeout: 5000,
        extra: {"context": context},
      );
      var client = Dio(options);
      client.interceptors.add(
        InterceptorsWrapper(
          onResponse: (response, handler) {
            CommonToast.dismissActivity();
            return handler.next(response);
          },
          onError: (error, handler) {
            CommonToast.dismissActivity();
            String msg;
            switch (error.type) {
              case DioErrorType.connectTimeout:
                msg = "连接超时错误";
                break;
              default:
                msg = "网络错误";
                break;
            }
            CommonToast.showError(msg);
          },
        ),
      );
      _client = client;
    }
  }

  Future<Response<T>> post<T>(
    String path, {
    Map<String, dynamic>? params,
    String? token,
  }) async {
    var options = Options(headers: {"Authorization": token});
    return await _client!.post(
      path,
      queryParameters: params,
      options: options,
    );
  }

  Future<Response<T>> get<T>(
    String path, {
    Map<String, dynamic>? params,
    String? token,
  }) async {
    var options = Options(headers: {"Authorization": token});
    return await _client!.get(
      path,
      queryParameters: params,
      options: options,
    );
  }

  Future<Response<T>> postFormData<T>(
    String path, {
    Map<String, dynamic>? params,
    String? token,
  }) async {
    var options = Options(
      contentType: ContentType.parse("multipart/form-data").value,
      headers: {"Authorization": token},
    );
    return await _client!.post(
      path,
      queryParameters: params,
      options: options,
    );
  }
}
